import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export function useTable(options = {}) {
  const {
    fetchData,
    deleteItem,
    batchDelete,
    defaultPageSize = 10,
    defaultSort = {},
    searchFields = []
  } = options

  // 表格状态
  const loading = ref(false)
  const tableData = ref([])
  const total = ref(0)
  const selectedRows = ref([])
  
  // 分页参数
  const pagination = reactive({
    current: 1,
    pageSize: defaultPageSize,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total, range) => `显示 ${range[0]}-${range[1]} 条，共 ${total} 条`,
    pageSizes: [10, 20, 50, 100]
  })

  // 排序参数
  const sortParams = ref({ ...defaultSort })

  // 搜索参数
  const searchParams = reactive({})

  // 筛选参数
  const filterParams = reactive({})

  // 计算属性
  const hasSelection = computed(() => selectedRows.value.length > 0)
  const isIndeterminate = computed(() => 
    selectedRows.value.length > 0 && selectedRows.value.length < tableData.value.length
  )
  const isAllSelected = computed(() => 
    selectedRows.value.length === tableData.value.length && tableData.value.length > 0
  )

  // 获取表格数据
  const loadData = async (params = {}) => {
    if (!fetchData) return

    loading.value = true
    try {
      const requestParams = {
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...sortParams.value,
        ...searchParams,
        ...filterParams,
        ...params
      }

      const response = await fetchData(requestParams)
      
      if (response) {
        tableData.value = response.data || response.list || []
        total.value = response.total || response.count || 0
        pagination.total = total.value
      }
    } catch (error) {
      ElMessage.error(error.message || '获取数据失败')
      tableData.value = []
      total.value = 0
      pagination.total = 0
    } finally {
      loading.value = false
    }
  }

  // 刷新数据
  const refresh = () => {
    loadData()
  }

  // 重置搜索
  const resetSearch = () => {
    Object.keys(searchParams).forEach(key => {
      searchParams[key] = ''
    })
    Object.keys(filterParams).forEach(key => {
      filterParams[key] = ''
    })
    pagination.current = 1
    loadData()
  }

  // 搜索
  const handleSearch = (params = {}) => {
    Object.assign(searchParams, params)
    pagination.current = 1
    loadData()
  }

  // 筛选
  const handleFilter = (params = {}) => {
    Object.assign(filterParams, params)
    pagination.current = 1
    loadData()
  }

  // 分页改变
  const handlePageChange = (page, pageSize) => {
    pagination.current = page
    pagination.pageSize = pageSize
    loadData()
  }

  // 页大小改变
  const handlePageSizeChange = (current, size) => {
    pagination.current = 1
    pagination.pageSize = size
    loadData()
  }

  // 排序改变
  const handleSortChange = ({ column, prop, order }) => {
    if (order) {
      sortParams.value = {
        sortField: prop,
        sortOrder: order === 'ascending' ? 'asc' : 'desc'
      }
    } else {
      sortParams.value = {}
    }
    pagination.current = 1
    loadData()
  }

  // 选择行
  const handleSelectionChange = (selection) => {
    selectedRows.value = selection
  }

  // 全选
  const handleSelectAll = (selection) => {
    selectedRows.value = selection
  }

  // 清除选择
  const clearSelection = () => {
    selectedRows.value = []
  }

  // 删除单项
  const handleDelete = async (row) => {
    if (!deleteItem) return

    try {
      await ElMessageBox.confirm(
        '确定要删除这条记录吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      loading.value = true
      await deleteItem(row.id || row)
      ElMessage.success('删除成功')
      
      // 如果当前页只有一条数据且不是第一页，则跳到上一页
      if (tableData.value.length === 1 && pagination.current > 1) {
        pagination.current -= 1
      }
      
      await loadData()
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error(error.message || '删除失败')
      }
    } finally {
      loading.value = false
    }
  }

  // 批量删除
  const handleBatchDelete = async () => {
    if (!batchDelete || selectedRows.value.length === 0) {
      ElMessage.warning('请选择要删除的记录')
      return
    }

    try {
      await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
        '批量删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      loading.value = true
      const ids = selectedRows.value.map(row => row.id)
      await batchDelete(ids)
      ElMessage.success('批量删除成功')
      
      clearSelection()
      
      // 重新计算当前页
      const remainingItems = total.value - selectedRows.value.length
      const maxPage = Math.ceil(remainingItems / pagination.pageSize)
      if (pagination.current > maxPage && maxPage > 0) {
        pagination.current = maxPage
      }
      
      await loadData()
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error(error.message || '批量删除失败')
      }
    } finally {
      loading.value = false
    }
  }

  // 导出数据
  const handleExport = async (exportFn, params = {}) => {
    if (!exportFn) return

    try {
      loading.value = true
      const exportParams = {
        ...searchParams,
        ...filterParams,
        ...params
      }
      
      const response = await exportFn(exportParams)
      
      // 处理文件下载
      if (response instanceof Blob) {
        const url = window.URL.createObjectURL(response)
        const link = document.createElement('a')
        link.href = url
        link.download = params.filename || `export_${Date.now()}.xlsx`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        
        ElMessage.success('导出成功')
      }
    } catch (error) {
      ElMessage.error(error.message || '导出失败')
    } finally {
      loading.value = false
    }
  }

  // 列设置
  const columnSettings = ref([])
  const visibleColumns = computed(() => 
    columnSettings.value.filter(col => col.visible)
  )

  const setColumnSettings = (columns) => {
    columnSettings.value = columns.map(col => ({
      ...col,
      visible: col.visible !== false
    }))
  }

  const toggleColumnVisible = (key) => {
    const column = columnSettings.value.find(col => col.key === key)
    if (column) {
      column.visible = !column.visible
    }
  }

  // 监听分页参数变化
  watch(
    () => [pagination.current, pagination.pageSize],
    () => {
      if (pagination.current !== 1 || pagination.pageSize !== defaultPageSize) {
        loadData()
      }
    }
  )

  return {
    // 状态
    loading,
    tableData,
    total,
    selectedRows,
    pagination,
    sortParams,
    searchParams,
    filterParams,
    columnSettings,
    
    // 计算属性
    hasSelection,
    isIndeterminate,
    isAllSelected,
    visibleColumns,
    
    // 方法
    loadData,
    refresh,
    resetSearch,
    handleSearch,
    handleFilter,
    handlePageChange,
    handlePageSizeChange,
    handleSortChange,
    handleSelectionChange,
    handleSelectAll,
    clearSelection,
    handleDelete,
    handleBatchDelete,
    handleExport,
    setColumnSettings,
    toggleColumnVisible
  }
}
